package cn.edu.lingnan.servlet.teacher;

import cn.edu.lingnan.pojo.Teacher;
import cn.edu.lingnan.service.TeacherService;
import cn.edu.lingnan.service.TeacherServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet({"/teacherpagequery", "/teacherquerybyname"})
public class TeacherServlet extends HttpServlet {
    private TeacherService  teacherService= new TeacherServiceImp();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getServletPath();

        switch (action) {
            case "/teacherpagequery":
                listTeachersByPage(request, response);
                break;
            case "/teacherquerybyname":
                searchTeachersByName(request, response);
                break;
        }
    }

    private void listTeachersByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int pageSize = 10;

        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        if (request.getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        List<Teacher> teachers = teacherService.pageQuery(page, pageSize);
        int totalTeachers = teacherService.getTotalTeachers();
        int totalPage = (int) Math.ceil(totalTeachers / (double) pageSize);

        request.setAttribute("teachers", teachers);
        request.setAttribute("currentPage", page);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPage", totalPage);

        request.getRequestDispatcher("teacher.jsp").forward(request, response);
    }

    private void searchTeachersByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String tname = request.getParameter("tname");

        List<Teacher> teachers = teacherService.getTeachersByName(tname);

        request.setAttribute("teachers", teachers);
        request.setAttribute("currentPage", 1);
        request.setAttribute("pageSize", teachers.size());
        request.setAttribute("totalPage", 1);

        request.getRequestDispatcher("teacher.jsp").forward(request, response);
    }
}